/*
 * EEPRomStream.h
 *
 *  Created on: 2012. 12. 6.
 *      Author: dalxx
 */

#ifndef EEPROMSTREAM_H_
#define EEPROMSTREAM_H_
#include "PLCLib/PLCConfig.h"
#include "StringStream.h"

class RingBuffer
{
protected:
	char buffer[EEPROM_WRITE_BUFFER_SIZE];
	int head, tail;
public:
	RingBuffer(){head=tail=0;}
	int read()
	{
		if(head!=tail)
		{
			int c=buffer[tail];
			tail=(++tail)%EEPROM_WRITE_BUFFER_SIZE;
			return c;
		}
		return -1;
	}
	int write(char c)
	{
		if(this->bufferSize()<EEPROM_WRITE_BUFFER_SIZE-1)
		{
			buffer[head]=c;
			head=(++head)%EEPROM_WRITE_BUFFER_SIZE;
			return c;
		}
		return -1;
	}
	int bufferSize()
	{
		int diff=(head-tail);
		return (diff>=0)?diff:diff+EEPROM_WRITE_BUFFER_SIZE;
	}


};
class EEPRomStream : public  StringStream {
private:
	static RingBuffer ringBuffer;
	int writeBuffer();
public:
	EEPRomStream();
	EEPRomStream(char* _buffer, int size);
	virtual ~EEPRomStream();
	virtual int read();
	virtual int peek();
	virtual size_t write(uint8_t byte);
	void flush();

	//void resetBuffer(int _buffer, int size);


};


#endif /* EEPROMSTREAM_H_ */
